package GameServer

import (
	. "PBMessage"
	. "SGNet"
	log "misc/seelog"
)

const (
	SERVERQUEUE_SIZE = 10
)

type GameServer struct {
	ModuleInfo

	clients       map[string]*ClientPlayer
	runningScenes map[int64]*GameScene
}

func NewGameServer() *GameServer {
	gameServer := &GameServer{}
	gameServer.ModuleInfo.New()
	gameServer.runningScenes = make(map[int64]*GameScene)
	gameServer.clients = make(map[string]*ClientPlayer)
	return gameServer
}

func (this *GameServer) OnLoad() {
	this.AddHandler(PBID_CS_Login, this.CS_Login_Handler)
	this.AddCommandHandler(CMD_GetServerNumber, this.CMD_GetServerNumber_Handler)
	this.AddCommandHandler(CMD_ClientLost, this.CMD_ClientLost)
	this.AddCommandHandler(CMD_RunNewScene, this.CMD_RunNewServer)
	this.ModuleInfo.Run()
}

//Player
func (this *GameServer) GetPlayer(userName string) *ClientPlayer {
	for _, v := range this.clients {
		if v.UserName == userName {
			return v
		}
	}
	return nil
}
func (this *GameServer) RemovePlayer(player *ClientPlayer) {
	delete(this.clients, player.UserName)
}

func (this *GameServer) AddPlayer(client *ClientPlayer) {
	this.clients[client.UserName] = client
}

func (this *GameServer) CMD_GetServerNumber_Handler(msg *Message) {
	ch := msg.Param["setnum"].(chan int)
	ch <- (len(this.clients))
}

func (this *GameServer) CMD_ClientLost(msg *Message) {
	sess := msg.Param["Sess"].(*Session)
	log.Info("Server移除玩家", sess.UserData.(*ClientPlayer).UserName)
	this.RemovePlayer(sess.UserData.(*ClientPlayer))
}

func (this *GameServer) AddGameScene(scene *GameScene) {
	this.runningScenes[scene.SceneID] = scene
}
func (this *GameServer) CMD_RunNewServer(msg *Message) {
	newScene := NewGameScene()
	this.AddGameScene(newScene)
	newScene.Init(msg.Param["Clients"].([]*ClientPlayer), msg.Param["Infos"].([]*ReadRoomPlayer))
}
